package com.kuaiditu.assistant.ui.authority;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.kuaiditu.assistant.R;
import com.kuaiditu.assistant.api.FileManager;
import com.kuaiditu.assistant.api.assistant_api.AssistantApi;
import com.kuaiditu.assistant.api.assistant_api.base.AssistantResponse;
import com.kuaiditu.assistant.base.BaseActivity;
import com.kuaiditu.assistant.common.Constants;
import com.kuaiditu.assistant.entity.AssistantUser;
import com.kuaiditu.assistant.module.retrofit.ProgressSubscriber;
import com.kuaiditu.assistant.ui.dialog.BottomDialog;
import com.kuaiditu.assistant.util.ToastUtil;
import com.kuaiditu.assistant.view.topbar.TopBar;
import com.miguelbcr.ui.rx_paparazzo2.RxPaparazzo;
import com.miguelbcr.ui.rx_paparazzo2.entities.FileData;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

@Route(path = AuthorityActivity.PATH, extras = Constants.NEED_LOGIN_EXTRA)
public class AuthorityActivity extends BaseActivity {
    public static final String PATH = "/user/auth";
    @BindView(R.id.top_bar)
    TopBar topBar;
    @BindView(R.id.img_idcard_front)
    ImageView imgIdcardFront;
    @BindView(R.id.img_idcard_reverse)
    ImageView imgIdcardReverse;
    @BindView(R.id.btn_commit)
    Button btnCommit;

    FileManager mFileManager;


    AssistantApi mAssistantApi;


    String idcardFront;
    String IdcardReverse;


    AssistantUser mAssistantUser;


    @Override
    public int initContentView() {
        return R.layout.activity_authority;
    }

    @Override
    public void initInjector() {
        mFileManager = getApplicationComponent().getApiManager().getFileManager();
        mAssistantApi = getApplicationComponent().getApiManager().getAssistantApi();
        mAssistantUser = getApplicationComponent().getUserStorage().getUser();
    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        topBar.bind(this, true);
    }


    @OnClick(R.id.img_idcard_front)
    public void onImgIdcardFrontClicked(final View v) {


        BottomDialog bottomDialog = (BottomDialog) ARouter.getInstance().build(BottomDialog.PATH).navigation();
        bottomDialog.setClickListener(new BottomDialog.OnClickListener() {
            @Override
            public void onChoiceItem(int pos) {
                choosePic((ImageView) v, pos);
            }

            @Override
            public void onCancel() {

            }
        });

        bottomDialog.show(getSupportFragmentManager(), BottomDialog.PATH);


    }

    @OnClick(R.id.img_idcard_reverse)
    public void onImgIdcardReverseClicked(final View v) {

        BottomDialog bottomDialog = (BottomDialog) ARouter.getInstance().build(BottomDialog.PATH).navigation();
        bottomDialog.setClickListener(new BottomDialog.OnClickListener() {
            @Override
            public void onChoiceItem(int pos) {
                choosePic((ImageView) v, pos);
            }

            @Override
            public void onCancel() {

            }
        });

        bottomDialog.show(getSupportFragmentManager(), BottomDialog.PATH);
    }

    @OnClick(R.id.btn_commit)
    public void onBtnCommitClicked() {
        commitAuth();
    }


//    private void upload(String path) {
//        mFileManager.uploadImg(path)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread());
//    }


    private void commitAuth() {

        if (TextUtils.isEmpty(idcardFront)) {
            ToastUtil.showToast("请上传身份证正面");
            return;
        }

        if (TextUtils.isEmpty(IdcardReverse)) {
            ToastUtil.showToast("请上传身份证手持照");
            return;
        }


        mAssistantApi.auth(idcardFront, IdcardReverse)
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onNext(AssistantResponse assistantResponse) {
                        mAssistantUser.setCourier_authFlag(1);
                        ToastUtil.showToast("认证已经提交，请耐心等待审核");
                        finish();
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }


    private void choosePic(final ImageView img, int src) {

        Observable<Response<AuthorityActivity, FileData>> observable;
        if (BottomDialog.CHOICE_TOOK == src) {

            observable = RxPaparazzo.single(this)
                    .crop()
                    .useInternalStorage()
                    .usingCamera();

        } else {
            observable = RxPaparazzo.single(this)
                    .crop()
                    .useInternalStorage()
                    .usingGallery();
        }



        observable.subscribeOn(Schedulers.io())
                .flatMap(new Function<Response<AuthorityActivity, FileData>, ObservableSource<AssistantResponse>>() {
                    @Override
                    public ObservableSource<AssistantResponse> apply(@NonNull Response<AuthorityActivity, FileData> response) throws Exception {
                        if (response.resultCode() == Activity.RESULT_OK) {
                            Glide.with(mContext).load(response.data().getFile().getAbsolutePath()).into(img);
                            return mFileManager.uploadImg(response.data().getFile().getAbsolutePath())
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread());
                        } else {
                            throw new IOException("没有选择图片");
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<AssistantResponse>(mContext) {
                    @Override
                    public void onNext(AssistantResponse assistantResponse) {
                        if (img == imgIdcardFront) {
                            idcardFront = assistantResponse.getRespData();
                        } else {
                            IdcardReverse = assistantResponse.getRespData();
                        }

                    }

                    @Override
                    public void onFinish() {

                    }
                });

    }


}
